import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../view/order_top_view.dart';
import '../../services/order_info_manger.dart';
import '../../models/order_list_model.dart';
import '../view/oredr_shai_view.dart';
import '../../components/order_item_widget.dart';
import '../controller/order_detail.dart';
import '../view/order_search_view.dart';
import '../../main.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> with AutomaticKeepAliveClientMixin {
  List<OrderArrayModel>? _orderList;
  bool _isLoading = false;
  int _pageNum = 1;
  int select = 0;
  String status = "";
  String date = "";
  String key = "";
  bool _showShaiView = false;
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
final GlobalKey<OrderSearchViewState> _searchViewKey = GlobalKey<OrderSearchViewState>();

  String _getStatusText(String status, AppLocalizations localizations) {
    switch (status) {
      case '0':
        return localizations.pendingPayment;
      case '1':
        return localizations.pendingShipment;
      case '2':
        return localizations.pendingReceipt;
      case '6':
        return localizations.afterSales;
      case '3':
        return localizations.completed;
      case '4':
        return localizations.canceled;
      case '5':
        return localizations.closed;
      case '7':
        return localizations.afterCompleted;
      case '8':
        return localizations.completeds;
      case '9':
        return localizations.completeds;
      default:
        return status;
    }
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      // _refreshController.requestRefresh(); // ✅ 主动触发刷新动画
      _loadData(isRefresh: true);
    });
  }

  Future<void> _loadData({bool isRefresh = false}) async {
    if (isRefresh) {
      _pageNum = 1; // 刷新时，重置 pageNum
    }

    if (!mounted) return; // 防止页面已销毁时setState出错
    setState(() {
      _isLoading = true;
    });

    final manager = OrederInfoManager();
    final params = {
      'date': date,
      'name': key,
      'orderId': '',
      'status': status,
      'pageNum': _pageNum,
      'pageSize': 10,
    };

    final success = await manager.loadInfoData(body: params);

    if (!mounted) return; // 防止页面已销毁时setState出错
    setState(() {
      _isLoading = false;
    });

    if (success.success) {
      if (isRefresh) {
        setState(() {
          _orderList = success.orderListModel; // 刷新时更新数据
        });
        _refreshController.refreshCompleted(); // 通知刷新完成
      } else {
        final newItems = success.orderListModel ?? [];
        if (newItems.isNotEmpty) {
          setState(() {
            _orderList?.addAll(newItems); // 上拉加载时追加数据
          });
        }
      }

      // 如果返回数据少于10条，说明没有更多数据了
      if (success.orderListModel == null || success.orderListModel!.length < 10) {
        _refreshController.loadNoData(); // 通知没有更多数据
      } else {
        _pageNum++; // 增加页码
        _refreshController.loadComplete(); // 通知加载完成
      }
    } else {
      if (isRefresh) {
        _refreshController.refreshFailed(); // 通知刷新失败
      } else {
        _refreshController.loadFailed(); // 通知加载失败
      }
    }
  }

@override
Widget build(BuildContext context) {
  final localizations = AppLocalizations.of(context)!;
  return Scaffold(
    body: Stack(
      children: [
        Column(
          children: [
            OrderTopView(
              onTabSelected: (index) {
                setState(() {
                  switch (index) {
                    case 0:
                      status = "";
                      break;
                    case 1:
                      status = "0";
                      break;
                    case 2:
                      status = "1";
                      break;
                    case 3:
                      status = "2";
                      break;
                    case 4:
                      status = "3";
                      break;
                  }
                  key = "";
                  _loadData(isRefresh: true);
                });
              },
              onFilter: () {
                setState(() {
                  _showShaiView = !_showShaiView;
                });
              },
              onSearch: () {
                // 显示搜索视图，隐藏筛选视图
                setState(() {
                  _showShaiView = false;
                });
                _searchViewKey.currentState?.show();
              },
            ),
            Expanded(
              child: SmartRefresher(
                controller: _refreshController,
                enablePullUp: true,
                onRefresh: () => _loadData(isRefresh: true),
                onLoading: () {
                  _loadData(isRefresh: false);
                },
                primary: false,
                header: WaterDropHeader(
                  complete: Text(AppLocalizations.of(context)!.pullToRefresh),
                  refresh: Text(AppLocalizations.of(context)!.loading),
                ),
                footer: ClassicFooter(
                  loadingText: AppLocalizations.of(context)!.loading,
                  idleText: AppLocalizations.of(context)!.releaseToLoad,
                  canLoadingText: AppLocalizations.of(context)!.releaseToLoad, // 添加canLoadingText控制释放加载提示
                  noDataText: "没有更多内容了", // 设置无更多数据时的提示文字
                ),
                child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _orderList == null || _orderList!.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              AppLocalizations.of(context)!.noneOrder,
                              style: const TextStyle(
                                color: Color(0xFF000000),
                                fontSize: 17,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              AppLocalizations.of(context)!.noneOrder2,
                              style: const TextStyle(
                                color: Color(0xFF666666),
                                fontSize: 15,
                              ),
                            ),
                            const SizedBox(height: 20),
                            SizedBox(
                              width: 107,
                              height: 36,
                              child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: const Color(0xFF5D5FEE),
                                  foregroundColor: Colors.white,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(18),
                                  ),
                                  textStyle: const TextStyle(fontSize: 15),
                                ),
                                onPressed: () {
                                  Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => MainPage(),
                                    ),
                                  );
                                },
                                child: Text(AppLocalizations.of(context)!.noneOrder3),
                              ),
                            ),
                          ],
                        ),
                      )
                    : ListView.builder(
                        key: const PageStorageKey<String>('order_list'),
                        padding: const EdgeInsets.symmetric(horizontal: 15),
                        itemCount: _orderList!.length,
                        itemBuilder: (context, index) {
                          final order = _orderList![index];
                          return OrderItemWidget(
                            order: order,
                            localizations: localizations,
                            getStatusText: _getStatusText,
                            copyIdTap: () async {
                              await Clipboard.setData(
                                  ClipboardData(text: order.orderId));
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                    content: Text(AppLocalizations.of(context)!
                                        .orderIdAlreadyCopy)),
                              );
                            },
                            onContentTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) =>
                                      OrderDetailPage(orderId: order.orderId),
                                ),
                              );
                            },
                          );
                        },
                      ),

              ),
            ),
          ],
        ),
        // ShaiView 显示在顶部
        if (_showShaiView)
        Positioned.fill( // ✅ 改成 fill，让蒙层覆盖整个屏幕
          child: OrderShaiView(
            selectData: select,
            clickShai: (date) {
              setState(() {
                select = date - 1;
                _showShaiView = false;
                this.date = date.toString();
                _loadData(isRefresh: true);
              });
            },
            clickSHide: () {
              setState(() {
                _showShaiView = false;
              });
            },
          ),
        ),


        // 顶部 OrderSearchView（固定高度 40，覆盖 OrderTopView）
        Positioned(
          top: MediaQuery.of(context).padding.top,
          left: 0,
          right: 0,
          height: 45,
          child: OrderSearchView(
            key: _searchViewKey,
            onSearchClick: (keyword) {
              date = "";
              key = keyword;
              // 回调时刷新数据
              _loadData(isRefresh: true);
            },
          ),
        ),
      ],
    ),
  );
}

}
